﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using cz.muni.fi.pb138.AdminService;
using System.Xml.Linq;
using cz.muni.fi.pb138.XML;
using System.Net;

namespace cz.muni.fi.pb138.Sessions
{
    public class AdminSession : IDisposable
    {
        AdminClient admin = new AdminClient();
        string sessionAdminId;
        public AdminSession()
        {
            admin.Open();
            sessionAdminId = admin.connect("admin", "testxml");
        }

		/// <summary>
		/// tests if the server can be connected to.
		/// </summary>
		/// <returns>true if the server connection is successful; false if not</returns>
        public static bool HasServerConnection()
        {
            HttpWebResponse response = null;
            try
            {
                String location = System.Configuration.ConfigurationManager.AppSettings["DatabaseAddress"];
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(location);
                request.Timeout = 5000;
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                if (response != null) response.Close();
            }
            return true;
        }

		/// <summary>
		/// Stores the given medium in a Database.
		/// </summary>
		/// <param name="mediumToStore"><c>Media</c> that is to be stored as an <c>XElement</c> class</param>
		/// <returns>an integer of utter destruction</returns>
        public int StoreMedium(XElement mediumToStore)
        {
            return admin.xupdateResource(sessionAdminId, MediaManager.Login, XmlHelper.CreateXUpdateAppend(mediumToStore));
        }

		/// <summary>
		/// Stores the given user in a database
		/// </summary>
		/// <param name="user">user name to be stored</param>
		/// <param name="password">password of a newly created DB</param>
        public void StoreUser(string user, string password)
        {
            admin.xupdateResource(sessionAdminId, "users", XmlHelper.CreateXUpdateAppendAddUser(user, password));

            CreateNewStorage(user);
        }

		/// <summary>
		/// Removes the given medium from a Database
		/// </summary>
		/// <param name="mediumToRemove"><c>Media</c> that is to be stored as an <c>XElement</c> class</param>
		/// <returns>an integer of utter destruction</returns>
        public int RemoveMedium(XElement mediumToRemove)
        {
            return admin.xupdateResource(sessionAdminId, MediaManager.Login, XmlHelper.CreateXUpdateRemove(mediumToRemove));
        }

		/// <summary>
		/// Updates a given medium. Updated is the medium with the same ID element.
		/// </summary>
		/// <param name="mediumToUpdate"><c>Media</c> that is to be stored as an <c>XElement</c> class</param>
		/// <returns>an integer of utter destruction</returns>
        public int UpdateMedium(XElement mediumToUpdate)
        {
            return admin.xupdateResource(sessionAdminId, MediaManager.Login, XmlHelper.CreateXUpdateUpdate(mediumToUpdate));
        }

		/// <summary>
		/// Disconnects from the database properly
		/// </summary>
        public void Dispose()
        {
            try
            {
                admin.disconnect(sessionAdminId);
                admin.Close();
            }
            catch { }
        }

		/// <summary>
		/// Creates new storage place in a database named by <c>personName</c>
		/// </summary>
		/// <param name="personName">the name of a new storage</param>
        private void CreateNewStorage(string personName)
        {

            XDocument initial = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement("medias"));

            admin.store(sessionAdminId, Encoding.Default.GetBytes((initial).ToString()), "UTF-8", personName, true);

        }

		/// <summary>
		/// Creates a new storage place to put new users and passwords to
		/// </summary>
        public void CreateNewPasswordStorage()
        {

            XDocument initial = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement("users"));

            admin.store(sessionAdminId, Encoding.Default.GetBytes((initial).ToString()), "UTF-8", "users", true);

        }
    }
}
